package com.lian.community.interceptor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

@Controller
@PropertySource(value = {"classpath:encoding.properties"},encoding="utf-8")
public class EncodingIntorceptor implements HandlerInterceptor{
    @Value("${encoding}")
    String encoding;

    private static final String[] REQUIRE_NOT_ENCODING_URLS = new String[]{
            ""
    };

    public boolean urlRequiredNotIntercept(String url){
        for(String containUrls : REQUIRE_NOT_ENCODING_URLS){
            if(url != null && url.equals(containUrls)){
                return true;
            }
        }
        return false;
    }


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String getUrl = httpServletRequest.getRequestURI();
        if(urlRequiredNotIntercept(getUrl)){
            return true;
        }
        try {
            httpServletRequest.setCharacterEncoding(encoding);
            httpServletResponse.setCharacterEncoding(encoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}
